<?php

namespace app\common\logic;

use app\common\library\exception\ApiException;
use app\common\library\MemberVo;
use app\common\model\Collection;
use app\common\model\OrderComment;
use app\common\model\OrderGoods;
use app\common\model\ShopGoods;
use app\common\model\ShopGoodsCollection;
use app\common\model\Tag;
use app\common\resourceHandle\ShopGoodsResource;
use think\db\Query;
use think\Env;

class ShopGoodsLogic extends BaseLogic
{
    public $model;

    public $resourceHandle;

    public function assignModel()
    {
        $this->model          = new ShopGoods();
        $this->resourceHandle = new ShopGoodsResource();
    }

    /**
     * 搜索条件处理
     * @param Query $query
     * @param array $params
     * @return Query
     */
    public function handleSearch(Query $query, array $params): Query
    {
        if (isset($params['status']) && $params['status'] !== '') {
            $query->where('status', $params['status']);
        }
        if (isset($params['audit_status']) && $params['audit_status'] !== '') {
            $query->where('audit_status', $params['audit_status']);
        }
        if (isset($params['shop_id'])  && $params['audit_status'] !== '') {
            $query->where('shop_id', $params['shop_id']);
        }
        $query->where('is_del', 0);
        return $query;
    }

    /**
     * 产品详情
     * @param array $params
     * @return \think\Model|null
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function info(array $params)
    {
        $info = $this->first(['goods_id' => $params['goods_id'], 'shop_id'  => $params['shop_id']],
            ['goods','goodsImage','shop',
                'comment'=>function($query){$query->order('fa_order_comment.id desc')->with(['member','commentImage'])->limit(2);},
//                'shop'=>function($query) use($params){$query->field("shop_name,phone,longitude,latitude,address,score,tags,business_start_time,business_end_time");},
                ]);
        if (!$info)
            throw new ApiException('商品信息不存在',404);
        $info['images'] = !empty($info['goods_image']) ? array_column($info['goods_image']->toArray(), 'image') : []; //轮播图处理
        $info['sale_num'] = OrderGoods::getSaleNumByShopGoodsId($params['shop_id'], $params['goods_id']);//销量
        $collection = Collection::get(['main_id'=>$info['id'],'service_type'=>0,'member_id'=>MemberVo::instance()->getMemberId()]);
        $info['is_collection'] = !empty($collection) ? 1 : 0;
        $info['collection_id'] = !empty($collection) ? intval($collection['id']) : 0;
        $info['goods_name'] = $info['goods']['goods_name'];//产品名称
        $info['business_start_time'] = $info['shop']['business_start_time'] ?? '';//营业开始时间
        $info['business_end_time'] = $info['shop']['business_end_time'] ?? '';//营业结束时间
        $info['goods_detail'] = $info['goods']['goods_detail'];//产品简介
        $info['note'] = $info['goods']['note'];//注意事项
        $price_info = ShopGoods::getPrice($info['market_price']);//价格
        $info['price'] = $price_info['price'];
        $info['price_tip'] =$price_info['price_tip'];//价格提示
        $info['goods_status'] = 1;
        //判断商品是否已下架
        if ($info['goods']['goods_status'] === 0 || $info['status'] === 0 || $info['audit_status'] != 1)
            $info['goods_status'] = 0;
        //商户信息
        $info['shop']['tags'] =  Tag::where(['id'=>['in',$info['shop']['tags']]])->column('name');
        if (isset($params['lat']) && !empty($params['lat'])){
            $info['shop']['distance'] = getDistance(['lat'=>$info['shop']['latitude'],'lng'=>$info['shop']['longitude'],'to'=>$params['lat'].','.$params['lng']]);//获取距离
            $info['shop']['distance'] = '距离'.$info['shop']['distance'].'km';
        }else{
            $info['shop']['distance'] = '';
        }
        $info['shop']['phone_arr'] = explode(',',$info['shop']['phone']);
        $info['recharge_info'] = ['image'=>Env::get('app.app_host').'/uploads/recharge/1.png','url'=>'/pages/client/balance/invest'];
        //商品评价
        if (!empty($info['comment'])){
            $arr['list'] = $info['comment']->toArray();
            $arr['praise_rate'] = '';
            unset($info['comment']);
            foreach ($arr['list']  as &$value){
                //评论名称获取
                $value['member_name'] = getCommentName($value['member']['member_name'],$value['anonymous']);
                $value['service_name'] = $info['goods_name'];
                $value['images'] = array_column($value['comment_image'],'image');
                unset($value['order_id'],$value['comment_image'],$value['shop_id'],$value['updatetime'],$value['deletetime'],$value['shop_goods_id'],$value['member_id'],$value['member']);
            }
            if (!empty($arr['list'])){
                //获取好评数
                $good_num = OrderComment::where(['shop_goods_id'=>$info['id'],'star'=>['gt',3]])->count('id');
                //获取总评论数
                $all_num = OrderComment::where(['shop_goods_id'=>$info['id']])->count('id');
                $arr['praise_rate'] = '0%';
                if ($all_num != 0){
                    $arr['praise_rate'] = round(($good_num/$all_num) *100,2).'%';
                }
            }
            $info['comment'] = $arr;
//            unset($info['comment']);
        }
        unset($info['cost'],$info['goods_image'],$info['createtime'],$info['updatetime'],$info['status'],$info['audit_status'],$info['sort'],$info['goods']);
        return $info;
    }

    /**
     * 客户端-产品列表
     * @param array $params
     * @return array
     * @throws \think\exception\DbException
     */
    public function list(array $params): array
    {
        $params['status'] = $this->enable;
        $params['audit_status'] = 1;
        $list             = $this->getList($params);
        return $this->resourceHandle->handleCollection($list);
    }

    /**
     * 商家端-产品列表
     * @param array $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function lists(array $params): array
    {
        $params['audit_status'] = ShopGoods::AUDIT_OK;
        $params['shop_id']      = $this->shopId;
        $params['orderBy']      = 'sort';
        $params['orderType']    = 'desc';
        $params['field']    = ['id,goods_id,price,cost,market_price,status'];
        $params['with']    = ['goods'];
        $list =  $this->getPageList($params)->toArray();
        foreach ($list['data'] as &$item){
            $item['goods_name'] = $item['goods']['goods_name'];
            $item['cover_img'] = $item['goods']['cover_img'];
            unset($item['goods']);
        }
        return $list;
    }

    /**
     * 产品上架
     * @param array $params
     * @return string
     * @throws ApiException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function putAway(array $params): string
    {
        $goods = $this->first([
            'goods_id' => $params['goods_id'],
            'shop_id'  => $this->shopId,
            'status'   => ShopGoods::STATUS_CLOSE,
        ]);
        if (!$goods) {
            throw new ApiException('商品不存在',404);
        }
        $goods->status = ShopGoods::STATUS_OK;
        $goods->save();
        return '上架成功';
    }

    /**
     * 产品下架
     * @param array $params
     * @return string
     * @throws ApiException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function soldOut(array $params): string
    {
        $goods = $this->first([
            'goods_id' => $params['goods_id'],
            'shop_id'  => $this->shopId,
            'status'   => ShopGoods::STATUS_OK,
        ]);
        if (!$goods) {
            throw new ApiException('商品不存在',404);
        }
        $goods->status = ShopGoods::STATUS_CLOSE;
        $goods->save();
        return '下架成功';
    }

    /**
     * 排序
     * @param $params
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function sort_old($params): int
    {
        $condition['status']       = $params['status'];
        $condition['audit_status'] = ShopGoods::AUDIT_OK;
        $condition['shop_id']      = $this->shopId;
        $condition['orderBy']      = 'sort';
        $condition['orderType']    = 'asc';
        $shopGoods                 = $this->getList($condition);

        $list = $shopGoods->toArray();
        foreach ($list as $k => &$li) {
            if ((int)$li['id'] === (int)$params['id']) {
                // 目标项取偏移量前后位置中值
                $tagSort = $k + (int)$params['offset'];
                if ($tagSort > $k) {
                    $tagSort = 2 * $tagSort + 1;
                } else {
                    $tagSort = 2 * $tagSort - 1;
                }
                $li['sort'] = $tagSort;
            } else {
                $li['sort'] = $k * 2;
            }
        }
        // 重新生成排序号
        $list = arraySequence($list, 'sort', 'SORT_ASC');
        foreach ($list as $index => &$value) {
            $value['sort'] = $index;
        }

        $list = array_column($list, null, 'id');
        // 保存
        foreach ($shopGoods as $item) {
            $item->sort = $list[$item->id]['sort'];
            $item->save();
        }
        return 1;
    }

    /**
     * 排序
     * @param $params
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function sort($params)
    {
        //获取当前商品的信息
        $info = ShopGoods::get($params['id']);
        if (!$info)
            throw new ApiException('商品信息不存在', 404);
        switch ($params['offset']) {
            case '-1'://上移
                //查询上一条产品信息
                $up_info = ShopGoods::where(['shop_id' => $info['shop_id'], 'status' => $info['status'], 'audit_status' => $info['audit_status'], 'sort' => ['gt', $info['sort']]])->order('sort asc')->find();
                if (!$up_info)
                    throw new ApiException('已经是第一条了', 404);
                ShopGoods::update(['sort' => $up_info['sort']], ['id' => $info['id']]);
                ShopGoods::update(['sort' => $info['sort']], ['id' => $up_info['id']]);
                break;
            case '1':
                //查询下一条产品信息
                $up_info = ShopGoods::where(['shop_id' => $info['shop_id'],'status' => $info['status'], 'audit_status' => $info['audit_status'], 'sort' => ['lt', $info['sort']]])->order('sort desc')->find();
                if (!$up_info)
                    throw new ApiException('已经是最后一条了', 404);
                ShopGoods::update(['sort' => $up_info['sort']], ['id' => $info['id']]);
                ShopGoods::update(['sort' => $info['sort']], ['id' => $up_info['id']]);
                break;
            default:
                throw new ApiException('不知所措的操作', 404);
        }
        return true;
    }
}